package lerry.utils;

import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.Lib;
import flash.system.System;
import flash.text.TextField;
import flash.text.TextFormat;
class FPS extends Sprite {
	var fps:Int;
	var show:TextField;
	var old:Int;
	var max:Float;
	var mem:Float;
	var bg:Shape;
	var ms:Int;
	var delay:Int;
	var temp:Int;
	
	var base:Float;
	public function new(size:Float=1) {
		super();
		old = Lib.getTimer();
		fps = 0;
		mem = 0;
		max = 0;
		ms = 0;
		base = System.totalMemory;
		show = new TextField();
		show.defaultTextFormat = new TextFormat("_sans", 10,0xffffff);
		
		show.width = 60;
		show.height = 50;
		show.scaleX = show.scaleY = size;
		show.selectable = false;
		addChild(show);
		
		graphics.beginFill(0xff0000, .5);
		graphics.drawRect(0, 0, width, height);
		graphics.endFill();
		
		scaleX = scaleY = size;
		
		addEventListener(Event.ADDED_TO_STAGE, added);
	}
	
	private function added(e:Event):Void {
		removeEventListener(Event.ADDED_TO_STAGE, added);
		addEventListener(Event.ENTER_FRAME, loop);
	}
	
	private function loop(e:Event):Void {
		this.parent.setChildIndex(this, this.parent.numChildren - 1);
		delay = Lib.getTimer();
		if (Lib.getTimer() - old > 1000) {
			old = Lib.getTimer();
			mem = ((System.totalMemory-base) / (1024 * 1024));
			max = max > mem?max:mem;
			temp = fps;
			fps = 0;
		}
		fps++;
		ms = delay - ms;
		show.text = "FPS:" + temp + "/" + stage.frameRate + "\nMEM:" + Std.string(mem).substr(0, 5) + "\nMAX:" + Std.string(max).substr(0, 5) + "\nMS:"+ms;
		ms = delay;
		
	}
}